package ch.zbw.sysventory.server.service.security.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import ch.zbw.sysventory.server.model.User;
import ch.zbw.sysventory.server.repository.UserRepository;
import ch.zbw.sysventory.server.service.security.PasswordService;
import ch.zbw.sysventory.server.service.security.UserRoleService;
import ch.zbw.sysventory.server.service.security.UserService;

@Transactional
@Service
public class UserServiceImpl implements UserService {

	@Autowired(required = true)
	private UserRepository userRepository;

	@Autowired(required = true)
	private UserRoleService userRoleService;

	@Autowired(required = true)
	private PasswordService passwordService;

	@Override
	public void changePassword(Long userId, String newPassword) throws Exception {
		User user = this.userRepository.findOne(userId);
		user.setPassword(this.passwordService.getMD5EncodedPassword(newPassword));
		this.userRepository.saveAndFlush(user);
	}

	@Override
	public void save(User user) throws Exception {
		user.setPassword(this.passwordService.getMD5EncodedPassword(user.getPassword()));
		this.userRepository.save(user);
	}

	@Override
	public void delete(Long id) {
		this.userRepository.delete(id);
	}

	@Override
	public User get(Long id) {
		return this.userRepository.findOne(id);
	}

	@Override
	public User update(User user) throws Exception {
		if (user.getPassword() != null && !"".equals(user.getPassword())) {
			user.setPassword(this.passwordService.getMD5EncodedPassword(user.getPassword()));
		} else {
			User oldUserObject = this.get(user.getId());
			user.setPassword(oldUserObject.getPassword());
		}
		return this.userRepository.saveAndFlush(user);
	}

	@Override
	@PreAuthorize("isAuthenticated()")
	public List<User> list() {
		return this.userRepository.findAll();
	}

	public void setUserDao(UserRepository userDao) {
		this.userRepository = userDao;
	}

	public void setPasswordService(PasswordService passwordService) {
		this.passwordService = passwordService;
	}

	@Override
	public User getByLoginName(String loginName) {
		return this.userRepository.getUserByLoginName(loginName);
	}

	@Override
	public User getNewUser() {
		User user = new User();
		user.setEnabled(true);
		user.setUserRole(this.userRoleService.getByName("Visitor"));
		return user;
	}

}
